package com.study.factory;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author Miss kun
 * @Date 2020/10/13 15:05
 * @Version 1.0
 */
public class HttpClient {

    public static void getURL(String url , HttpServletResponse response1) {
//        HashMap<String, String> headers = new HashMap<String, String>();
//        headers.put("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 Greatwqs");
//        headers.put("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//        headers.put("Accept-Language","zh-cn,zh;q=0.5");
//        headers.put("Host","www.dushu.com");
//        headers.put("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
//        headers.put("Referer", "https://www.dushu.com/lianzai/1115.html");
        HttpRequestBase httpget = new HttpGet(url);
        httpget.setHeader("Referer", "https://www.dushu.com/lianzai/1115.html");
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpget);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将图片或者文件转化成数组的形式
                byte[] data = EntityUtils.toByteArray(responseEntity);
                // 获取输出流
                OutputStream toClient = response1.getOutputStream();
                // 将这个数组写入输出流中
                toClient.write(data);
                toClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
    }
}

